import http from '@/utils/request.ts'
import type { 
  TodoItem, 
  CreateTodoRequest, 
  UpdateTodoRequest,
  TodoCategory
} from '@/modules/todo/types/todo.ts'

// 待办事项查询参数
export interface TodoListQuery {
  categoryId?: string | -1
  status?: string
  priority?: string
  keyword?: string
  isFavorite?: boolean
}

// 转换待办事项ID为字符串
function convertTodoIds(todo: any): TodoItem {
  return {
    ...todo,
    id: String(todo.id),
    categoryId: todo.categoryId ? String(todo.categoryId) : undefined,
    createdTime: todo.createdTime || todo.createdAt,
    updatedAt: todo.updatedTime || todo.updatedAt
  }
}

// 转换分类ID为字符串
function convertCategoryIds(category: any): TodoCategory {
  return {
    ...category,
    id: String(category.id)
  }
}

export const todoApi = {
  // 获取待办事项列表（支持筛选）
  getList: async (query?: TodoListQuery): Promise<TodoItem[]> => {
    let url = '/todo/list'
    const params = new URLSearchParams()

    if (query?.categoryId !== undefined) {
      if (query.categoryId === -1) {
        params.append('categoryId', '-1')
      } else {
        params.append('categoryId', String(query.categoryId))
      }
    }

    if (query?.status) {
      params.append('status', query.status)
    }

    if (query?.priority) {
      params.append('priority', query.priority)
    }

    if (query?.keyword) {
      params.append('keyword', query.keyword)
    }

    if (query?.isFavorite !== undefined) {
      params.append('isFavorite', String(query.isFavorite))
    }

    if (params.toString()) {
      url += '?' + params.toString()
    }

    const response = await http.get<any[]>(url)
    const data = response.data || []
    return data.map(convertTodoIds)
  },

  // 根据ID获取待办事项
  getById: async (id: string): Promise<TodoItem> => {
    const response = await http.get<any>(`/todo/${id}`)
    return convertTodoIds(response.data)
  },

  // 创建待办事项
  create: async (request: CreateTodoRequest): Promise<TodoItem> => {
    const response = await http.post<any>('/todo', request)
    return convertTodoIds(response.data)
  },

  // 更新待办事项
  update: async (id: string, request: UpdateTodoRequest): Promise<TodoItem> => {
    const response = await http.put<any>(`/todo/${id}`, request)
    return convertTodoIds(response.data)
  },

  // 删除待办事项
  delete: async (id: string): Promise<boolean> => {
    const response = await http.delete<boolean>(`/todo/${id}`)
    return response.data
  },

  // 切换待办事项状态
  toggleStatus: async (id: string): Promise<TodoItem> => {
    const response = await http.put<any>(`/todo/${id}/toggle-status`)
    return convertTodoIds(response.data)
  },

  // 批量更新状态
  batchUpdateStatus: async (ids: string[], status: string): Promise<boolean> => {
    const response = await http.put<boolean>(`/todo/batch-status?status=${status}`, { ids })
    return response.data
  }
}

export const todoCategoryApi = {
  // 获取所有分类
  getList: async (): Promise<TodoCategory[]> => {
    const response = await http.get<any[]>('/todo-category/list')
    const data = response.data || []
    return data.map(convertCategoryIds)
  },

  // 根据ID获取分类
  getById: async (id: string): Promise<TodoCategory> => {
    const response = await http.get<any>(`/todo-category/${id}`)
    return convertCategoryIds(response.data)
  },

  // 创建分类
  create: async (request: { name: string; color: string; icon?: string }): Promise<TodoCategory> => {
    const response = await http.post<any>('/todo-category', request)
    return convertCategoryIds(response.data)
  },

  // 更新分类
  update: async (id: string, request: { name: string; color: string; icon?: string }): Promise<TodoCategory> => {
    const response = await http.put<any>(`/todo-category/${id}`, request)
    return convertCategoryIds(response.data)
  },

  // 删除分类
  delete: async (id: string): Promise<boolean> => {
    const response = await http.delete<boolean>(`/todo-category/${id}`)
    return response.data
  }
}